package com.catazy.wanandroid.common_base.ext

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.catazy.wanandroid.common_base.BaseApplication
import kotlinx.coroutines.flow.map

/**
 * 作者: Tao
 * 日期: 2024/5/13
 * 时间: 14:18
 * 描述: sharedPreference,内核基于DataStore
 */
object Pref {

    /**
     * dataStore 存入数据默认就是异步，没有同步方法
     * 取数据异步通过Flow实现
     */
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

    /**
     * 存储数据
     * @param key 键
     * @param value 值
     */
    suspend fun put(key: String, value: Any) {
        when (value) {
            is String -> BaseApplication.getContext().dataStore.edit { settings ->
                settings[stringPreferencesKey(key)] = value
            }

            is Int -> BaseApplication.getContext().dataStore.edit { settings ->
                settings[intPreferencesKey(key)] = value
            }

            is Boolean -> BaseApplication.getContext().dataStore.edit { settings ->
                settings[booleanPreferencesKey(key)] = value
            }

            is Float -> BaseApplication.getContext().dataStore.edit { settings ->
                settings[floatPreferencesKey(key)] = value
            }

            is Long -> BaseApplication.getContext().dataStore.edit { settings ->
                settings[longPreferencesKey(key)] = value
            }
        }
    }

    /**
     * 获取数据
     * @param key 键
     * @param default 默认值
     */
    suspend fun <T> get(key: String, default: T): T {
        return when (default) {
            is String -> BaseApplication.getContext().dataStore.data.map { settings ->
                settings[stringPreferencesKey(key)] ?: default
            }

            is Int -> BaseApplication.getContext().dataStore.data.map { settings ->
                settings[intPreferencesKey(key)] ?: default
            }

            is Boolean -> BaseApplication.getContext().dataStore.data.map { settings ->
                settings[booleanPreferencesKey(key)] ?: default
            }

            is Float -> BaseApplication.getContext().dataStore.data.map { settings ->
                settings[floatPreferencesKey(key)] ?: default
            }

            is Long -> BaseApplication.getContext().dataStore.data.map { settings ->
                settings[longPreferencesKey(key)] ?: default
            }

            else -> throw IllegalArgumentException("This type can be saved into DataStore")
        } as T
    }
}